﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace ReValidator
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnValidate_Click(object sender, EventArgs e)
        {
            string pattern = txtPattern.Text;
            if (pattern.Length==0)
            {
                //TODO
                return;
            }
            Regex re = new Regex(pattern);

            string source = txtSource.Text;

            MatchCollection matches = re.Matches(source);
            tvResult.Nodes.Clear();
            foreach (Match match in matches)
            {
                TreeNode matchNode = new TreeNode(match.Value);
                matchNode.Tag = new PosInfo(match.Index, match.Length);

                bool firstGroup = true;
                foreach (Group group in match.Groups)
                {
                    if (firstGroup) {
                        firstGroup = false; 
                        continue;
                    }

                    TreeNode groupNode = new TreeNode(group.Value);
                    groupNode.Tag = new PosInfo(group.Index, group.Length);
                    matchNode.Nodes.Add(groupNode);
                }

                tvResult.Nodes.Add(matchNode);
            }
        }

        private void btnLoadURL_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            string url = txtURL.Text.Trim();
            if (url.Length==0) return;

//            txtSource.Text = new WebClient().DownloadString(url);
            txtSource.Text = downloadWebPage(url);

            this.Cursor = Cursors.Default;
        }

        string downloadWebPage(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader streamReader = new StreamReader(response.GetResponseStream());

            return streamReader.ReadToEnd();
        }

        private void btnQuit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }

    class PosInfo
    {
        public int Index { get; set; }
        public int Length { get; set; }

        public PosInfo(int index, int length)
        {
            this.Index = index;
            this.Length = length;
        }
    }
}
